package net.dgg.zz.common.service;

import net.dgg.framework.tac.utils.idutil.DggKeyWorker;
import net.dgg.iboss.base.service.ArService;
import net.dgg.iboss.base.util.CustomerNumberEncryptionUtil;
import net.dgg.iboss.base.util.DesUtil;
import net.dgg.tmd.foundation.platform.common.util.TranslateUtil;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import net.dgg.tmd.foundation.platform.user.service.UserManager;
import net.dgg.zz.common.base.service.BaseService;
import net.dgg.zz.common.dao.ZzFilesRecordDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.*;

@Service
public class ZzFilesRecordService extends BaseService {
    @Autowired
    private ZzFilesRecordDao scFilesRecordDao;
    @Autowired
    private SessionManager sessionManager;
    @Autowired
    private ArService arService;
    @Autowired
    private UserManager userManager;
    @Autowired
    private DesUtil desUtil;
    @Autowired
    private TranslateUtil translateUtil;
    private String[] insertCols = new String[]{"filesId", "filesNo", "orderId", "orderNo", "filesCustomerName", "filesStatus", "filesLocation"};


    /**
     * 查询有效的档案绑定记录
     *
     * @param orderId 生产子订单id
     * @return
     */
    public List<Map> query(String orderId) {
        Assert.notNull(orderId, "缺少必要参数：orderId！");
        Map para = new HashMap();
        para.put("orderId", orderId);
        return scFilesRecordDao.queryMap(para);

    }

    /**
     * 查询有效档案绑定的记录个数
     *
     * @param orderId 生产子订单id
     * @return
     */
    public int count(String orderId) {
        Assert.notNull(orderId, "缺少必要参数：orderId！");
        Map para = new HashMap();
        para.put("orderId", orderId);
        return scFilesRecordDao.count(para);
    }

    /**
     * 使一条绑定记录失效（解绑该条记录所记录的档案）
     */
    public void invalid(Map paras) {
        UserEntity user;
        if (paras.containsKey("appUserId")) {
            user = userManager.findUserById(Long.valueOf(paras.get("appUserId") + ""));
        } else {
            user = sessionManager.getCurrentUser();
        }
        Assert.notNull(paras.get("filesId"), "缺少必要参数：filesId！");
        Assert.notNull(paras.get("orderId"), "缺少必要参数：orderId！");

        setUpdater(paras, user);
        scFilesRecordDao.invalid(paras);
    }

    /**
     * 插入一条新的绑定记录
     */
    @Transactional
    public void insert(Map record) {

        UserEntity user;
        if (record.containsKey("appUserId")) {
            user = userManager.findUserById(Long.valueOf(record.get("appUserId") + ""));
        } else {
            user = sessionManager.getCurrentUser();
        }
        //
        for (String name : insertCols) {
            String p = record.get(name) + "";
            Assert.isTrue(!p.equals(""), String.format("缺少必要参数：%s！", name));
        }
        setCreator(record, user);
        record.put("id", DggKeyWorker.nextId());
        record.put("bindStatus", 1);
        scFilesRecordDao.insert(record);
    }

    /**
     * 绑定多条档案
     *
     * @param user
     * @param order
     * @param filesList
     */
    @Transactional
    public void insert(UserEntity user, Map order, List<Map> filesList) {
        Assert.notNull(user, "未找到用户！");

        for (Map record : filesList) {

            record.put("scProductId", order.get("id"));
            record.put("scProductNo", order.get("scProductOrderNo"));
            record.put("orderProductName", order.get("productName"));
            setCreator(record, user);
            record.put("id", DggKeyWorker.nextId());
            record.put("bindStatus", 1);
            scFilesRecordDao.insert(record);

        }

    }

    public List<Map> queryFiles(Map paras) {
        Map colMapper = new HashMap<String, String>();
        int count = 0;
        List<Map> filesList = new ArrayList<Map>() {
        };
        colMapper.put("customeCode", "filesCustomerNo");
        colMapper.put("customerName", "filesCustomerName");
        colMapper.put("id", "filesId");
        colMapper.put("no", "filesNo");
        colMapper.put("seat", "filesLocation");
        colMapper.put("status", "filesStatus");
        //查询参数start 改page

        int start = Integer.parseInt(paras.get("start") + "");
        int limit = Integer.parseInt(paras.get("limit") + "");
        start = start / limit + 1;
        paras.put("page", start);
        //
        Map result = arService.queryPinlessDate(paras);
        if (result != null && result.size() > 0) {
            String totalCount = result.get("totalCount") + "";
            count = Integer.parseInt(totalCount);
            filesList = (List<Map>) result.get("bagList");
        }

        for (Map files : filesList) {
            Iterator<String> it = colMapper.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                if (files.containsKey(key)) {
                    files.put(colMapper.get(key), files.get(key));
                    files.remove(key);
                }
            }
        }

        paras.put("totalCount", count);
        return filesList;

    }

    /**
     * 根据档案编号查询有效的绑定记录
     *
     * @param filesNo
     * @return
     */
    public List<Map> queryRecordByFiles(String filesNo) {
        Map map = new HashMap();
        map.put("filesNo", filesNo);
        List<Map> resultList = scFilesRecordDao.queryMapWithOrderInfo(map);
        //翻译
        resultList = translateUtil.translateList(new String[]{"orderStatus"}, resultList);
        //解密
        resultList = desUtil.decryptListMap(new String[]{"orderCustomerPhone", "orderCustomerPhoneCopy"}, resultList);
        //脱敏
        CustomerNumberEncryptionUtil.encryptionList(new String[]{"orderCustomerPhone"}, resultList);
        return resultList;
    }

    private void setCreator(Map para, UserEntity user) {
        para.put("createTime", new Date());
        para.put("creatorId", user.getId());
        para.put("creatorName", user.getRealName() + user.getLoginName());
        para.put("creatorOrgId", user.getOrgId());
    }

    private void setUpdater(Map para, UserEntity user) {
        para.put("updaterId", user.getId());
        para.put("updaterName", user.getRealName() + user.getLoginName());
        para.put("updaterOrgId", user.getOrgId());
    }
}
